package com.example.bbang.controller;

import com.example.bbang.common.CommonResult;
import com.example.bbang.entity.Order;

import com.example.bbang.entity.User;

import com.example.bbang.mapper.OrderMapper;
import com.example.bbang.service.MessageProducer;
import com.example.bbang.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.RedisLock;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    OrderService orderService;
    @Resource
    OrderMapper orderMapper;

    @Autowired
    private MessageProducer messageProducer;


    private final RedisLock redisLock;
    @Autowired
    public OrderController(RedisLock redisLock) {
        this.redisLock =redisLock;
    }


    @GetMapping("/unac")
    public CommonResult getOrderByState(Integer orderStatus,String username) {
        return CommonResult.ok(orderService.getOrderByState(orderStatus,username)) ;
    }

    @GetMapping("/byname")
    public CommonResult getOrderById(String bname,Integer orderStatus){

    System.out.println(bname);
        System.out.println(orderStatus);
    return CommonResult.ok(orderService.getOrderById(bname,orderStatus)) ;
    }

    @GetMapping("/byid")
    public CommonResult getOrderById1(Integer orderid){
        return CommonResult.ok(orderMapper.getOrderById1(orderid)) ;
    }



    @GetMapping()    public CommonResult getOrder(){        return CommonResult.ok(orderService.getOrder()) ;    }


    //分页拿order
//    分页查询
//    接口路径：/order/page?pageNum=1&pageSize=10
//    @RequestParam接收
//    limit第一个参数= （pageNum-1)+pageSize
    @GetMapping("/page")
    public CommonResult findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize ,HttpServletRequest req){
        System.out.println(pageNum+"和"+pageSize);
        // pageNum = (pageNum-1);

        System.out.println("userSession2222"+req.getServletContext().getAttribute("User"));
        return CommonResult.ok(orderMapper.selectPage(pageNum,pageSize)) ;

    }
        @GetMapping("/pageByType")
    public CommonResult pageByType(@RequestParam Integer pageNum, @RequestParam Integer pageSize,@RequestParam Integer type){
        System.out.println(pageNum+"和"+pageSize+"和"+type);

        return CommonResult.ok(orderMapper.pageByType(pageNum,pageSize,type)) ;

    }

         @GetMapping("/pageByOrderStatusAndType")
    public CommonResult pageByOrderStatusAndType(@RequestParam Integer pageNum, @RequestParam Integer pageSize,@RequestParam Integer orderStatus,@RequestParam Integer type){
        System.out.println(pageNum+"和"+pageSize+"和"+orderStatus+"和"+type);

        return CommonResult.ok(orderMapper.pageByOrderStatusAndType(pageNum,pageSize,orderStatus,type)) ;

    }


    @GetMapping("/pagename")
    public CommonResult findPageByOrderName(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String orderName){
        if (orderName=="")
        {
            System.out.println(pageNum+"和"+pageSize);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.selectPage(pageNum,pageSize)) ;
        }
        System.out.println(pageNum+"和"+pageSize+"和"+orderName);
        // pageNum = (pageNum-1);
        return CommonResult.ok(orderMapper.findPageByOrderName(pageNum,pageSize,orderName)) ;

    }

//bs拿order
    @GetMapping("/bspagename")
    public CommonResult BSfindPageByOrderName(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String orderName,@RequestParam Integer orderStatus){
        if (orderName=="")
        {
            System.out.println(pageNum+"和"+pageSize);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.bsselectPage(pageNum,pageSize,orderStatus)) ;
        }
        System.out.println(pageNum+"和"+pageSize+"和"+orderName+"和"+orderStatus);
        // pageNum = (pageNum-1);
        return CommonResult.ok(orderMapper.bsfindPageByOrderName(pageNum,pageSize,orderName,orderStatus)) ;

    }




    @GetMapping("/pagestatus")
    public CommonResult findPageByOrderStatus(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam Integer orderStatus,@RequestParam String orderName,@RequestParam String username){
        if (orderStatus==0)
        {
            System.out.println(pageNum+"和1     "+pageSize+"和"+orderStatus+"和"+username+"和"+orderName);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.findPageByOrderOrdername(pageNum,pageSize,orderName,username)) ;
        }
        if (orderName==""&&orderStatus!=0)
        {
            System.out.println(pageNum+"和2     "+pageSize+"和"+orderStatus+"和"+username+"和"+orderName);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.findPageByOrderStatus1(pageNum,pageSize,orderStatus,username)) ;
        }



        System.out.println(pageNum+"和3    "+pageSize+"和"+orderStatus+"和"+username+"和"+orderName);
        // pageNum = (pageNum-1);
        return CommonResult.ok(orderMapper.findPageByOrderStatus(pageNum,pageSize,orderStatus,orderName,username)) ;

    }

//bs
    @GetMapping("/bspagestatus")
    public CommonResult bsfindPageByOrderStatus(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam Integer orderStatus,@RequestParam String orderName,@RequestParam String bname){
       if(orderStatus!=0)
       {
           orderStatus+=1;
       }
        if (orderStatus==0)
        {
            System.out.println(pageNum+"和1     "+pageSize+"和"+orderStatus+"和"+bname+"和"+orderName);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.bsfindPageByOrderOrdername(pageNum,pageSize,orderName,bname)) ;
        }
        if (orderName==""&&orderStatus!=0)
        {
            System.out.println(pageNum+"和2     "+pageSize+"和"+orderStatus+"和"+bname+"和"+orderName);
            // pageNum = (pageNum-1);

            return CommonResult.ok(orderMapper.bsfindPageByOrderStatus1(pageNum,pageSize,orderStatus,bname)) ;
        }



        System.out.println(pageNum+"和3    "+pageSize+"和"+orderStatus+"和"+bname+"和"+orderName);
        // pageNum = (pageNum-1);
        return CommonResult.ok(orderMapper.bsfindPageByOrderStatus(pageNum,pageSize,orderStatus,orderName,bname)) ;

    }



    @PostMapping("addOrderById")
    public CommonResult addOrderById( Order order){
       Order o = orderService.addOrderById(order);
       if (o==null){
           System.out.println("加order失败");
           return CommonResult.ok("添加order失败");
       }
        System.out.println("加order成功:"+o);
        return CommonResult.ok("添加order成功");
    }

    //    抢单接口
    @PostMapping("/update")
    public CommonResult updateUser(Order order) {
        System.out.println("是否抢单：" + order.getYnQiangDan());
        // 等于1则为抢单，否则为更新订单信息
        if (order.getYnQiangDan() == 1) {
            System.out.println("更新order:" + order);
            System.out.println(order.getOrderid() + order.getBname() + order.getOrderStatus());
            String requestId = java.util.UUID.randomUUID().toString();
            String lockKey = "order:" + order.getOrderid();

            boolean locked = redisLock.tryLock(lockKey, requestId);
            if (locked) {
                // 如果能过获取到锁
                try {
                    // 根据orderid去查orderstatus是否为0，也就是未接单状态
                    boolean success = orderService.grabOrder(Long.valueOf(order.getOrderid()), order.getBname());
                    if (success) {
                        orderService.updateById(order);
                        // 生产者：负责创建和发送消息到消息队列
                        System.out.println("生产者：创建消息 '用户" + order.getBname() + "抢单成功' 并发送到消息队列，路由键为 'order.grab.success'");
                        messageProducer.sendOrderMessage("用户" + order.getBname() + "抢单成功", "order.grab.success");
                        return CommonResult.ok("抢单成功");
                    } else {
                        // orderstatus不等于0的时候走这里
                        System.out.println("用户" + order.getBname() + "抢单失败,任务已被抢完");
                        // 生产者：负责创建和发送消息到消息队列
                        System.out.println("生产者：创建消息 '用户" + order.getBname() + "抢单失败,任务已被抢完' 并发送到消息队列，路由键为 'order.grab.fail'");
                        messageProducer.sendOrderMessage("用户" + order.getBname() + "抢单失败,任务已被抢完", "order.grab.fail");
                        return CommonResult.noOk("任务已被抢完");
                    }
                } finally {
                    // 不管如何都释放锁
                    redisLock.releaseLock(lockKey, requestId);
                }
            } else {
                // 1抢单的过程中（还没释放锁），2发起了抢单请求，则走这里
                System.out.println("用户" + order.getBname() + "抢单失败,任务正在被其他用户抢");
                // 生产者：负责创建和发送消息到消息队列
                System.out.println("生产者：创建消息 '用户" + order.getBname() + "抢单失败,任务正在被其他用户抢' 并发送到消息队列，路由键为 'order.grab.fail'");
                messageProducer.sendOrderMessage("用户" + order.getBname() + "抢单失败,任务正在被其他用户抢", "order.grab.fail");
                return CommonResult.noOk("抢单失败，任务正在被其他用户抢");
            }
        } else {
            orderService.updateById(order);
            // 生产者：负责创建和发送消息到消息队列
            System.out.println("生产者：创建消息 '订单信息更新成功' 并发送到消息队列，路由键为 'order.update.success'");
            messageProducer.sendOrderMessage("订单信息更新成功", "order.update.success");
            return CommonResult.ok("success");
        }
    }


    @PostMapping ("/bupdate")
    public CommonResult bUpdate( Order order){
        orderService.updateByName(order);
        return CommonResult.ok("success") ;
    }



    @PostMapping ("/delete")
    public CommonResult deleteUser( Order order){
        orderService.deleteById(order);
        return CommonResult.ok("success") ;
    }

    @GetMapping("/countOrderByOrderStatus")
    public CommonResult countOrderByOrderStatus(String orderStatus){
        return CommonResult.ok(orderService.countOrderByOrderStatus(orderStatus)) ;
    }

    @GetMapping("/countOrder")
    public CommonResult countOrder(){
        return CommonResult.ok(orderService.countOrder()) ;
    }


//    抢单接口
//@PostMapping("/grab/{orderId}")
//public String grabTask(@PathVariable("orderId") Long orderId, @RequestParam("userId") Long userId) {
//    String requestId = java.util.UUID.randomUUID().toString();
//    String lockKey = "order:" + orderId;
//
//    System.out.println("requestId:"+requestId+"\n"+"lockKey:"+lockKey);
//
//    boolean locked = redisLock.tryLock(lockKey, requestId);
//    if (locked) {
//        //如果能过获取到锁
//        try {
//            boolean success = orderService.grabTask(orderId, userId);
//            if (success) {
//                return "抢单成功";
//            } else {
//                System.out.println("用户"+userId+"抢单失败,任务已被抢完");
//                return "任务已被抢完";
//            }
//        } finally {
//            redisLock.releaseLock(lockKey, requestId);
//        }
//    } else {
//        System.out.println("用户"+userId+"抢单失败,任务正在被其他用户抢");
//        return "抢单失败，任务正在被其他用户抢";
//    }
//}





}
